﻿using System;
using System.Collections.Generic;
using System.Data;
using Utils;

namespace StockAnalyst2.Plugins.Visualization.Realtime
{
	internal class NotificationDataSource
	{
		#region Attributes

		private readonly IDataBaseClient _dbclient;

		#endregion

		#region Constants

		private const string NotificationsQuery = "SELECT TOP {0} [Date], [Message] FROM [Notifications] ORDER BY [Date] DESC";
		private const string InsertNotification = "INSERT INTO [Notifications] ([Date], [Message]) VALUES (CONVERT(datetime2, '{0}', 103), '{1}')";

		#endregion

		#region Public Methods

		public NotificationDataSource(IDataBaseClient dbclient)
		{
			_dbclient = dbclient;
		}

		public List<Notification> Load()
		{
			List<Notification> result = new List<Notification>();

			DataTable data = _dbclient.ExecuteQuery(string.Format(NotificationsQuery, Properties.Settings.Default.MaxRealtimeNotifications));

			for (int index = data.Rows.Count - 1; index > 0; index--) 
			{
				result.Add(new Notification((DateTime)data.Rows[index]["Date"], data.Rows[index]["Message"].ToString()));
			}

			return result;
		}

		public void Save(Notification notification)
		{
			_dbclient.ExecuteCommand(string.Format(InsertNotification, notification.Date.ToString("dd/MM/yyyy HH:mm:ss:fff"), notification.Message));
		}

		#endregion

	}
}
